package com.assessment.service.impl;

import com.assessment.service.DownLoadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.URLDecoder;

import static com.assessment.utils.Constant.*;
import static java.nio.charset.StandardCharsets.UTF_8;

@Service
@Transactional
public class DownLoadServiceImpl implements DownLoadService {

    private static final Logger log = LoggerFactory.getLogger(DownLoadServiceImpl.class);
    @Value("${file.base.path}")
    private String BASE_PATH;

    @Override
    public ResponseEntity<Object> getFile(String fileFolder, String fileName) throws Exception{

        String path = BASE_PATH + "/"+fileFolder+"/"+getFileName(fileName);
        log.info("path:{}", path);

        String contentDisposition = ContentDisposition
                .builder("attachment")
                .filename(getFileNameWithEnd(fileName),UTF_8)// 文件名去除时间戳
                .build().toString();
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(new FileSystemResource(path));
    }
    private String getFileName(String fileName){
        switch (fileName) {
            case DOWNLOAD_ROLE:
                return "role.xlsx";
            case DOWNLOAD_DEP:
                return "dep.xlsx";
            case DOWNLOAD_PEO:
                return "peo.xlsx";
            default:
                return fileName;
        }
    }
    private String getFileNameWithEnd(String fileName){
        switch (fileName) {
            case DOWNLOAD_ROLE:
                return "角色导入模板.xlsx";
            case DOWNLOAD_DEP:
                return "部门导入模板.xlsx";
            case DOWNLOAD_PEO:
                return "人员导入模板.xlsx";
            default:
                return fileName.substring(fileName.indexOf("-")+1);
        }
    }

}
